<template>
  <el-dialog
    v-show="dialogPhoneVisible"
    :modal-append-to-body="false"
    :title="activeName==='2'? '输入手机号码': '输入短信验证码'"
    :visible="dialogPhoneVisible"
    @close="dialogCloseFn()"
    center
    width=400px
    :show-close=false
    :close-on-click-modal='false'
  >
    <el-tabs
      v-model="activeName"
      type="card"
    >
      <el-tab-pane name="1">
        <el-form
          :model="codeFrom"
          ref="codeFrom"
          :rules='codeRules'
          label-width='70px'
        >
          <el-form-item label="手机号">
            <el-input
              v-model.trim="userInfo.phone"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="验证码"
            prop='code'
          >
            <div
              class="refetch"
              style="width: 400px ;display: flex"
            >
              <el-input
                style="width: 145px; margin-right: 10px;"
                v-model.trim="codeFrom.code"
                clearable
                minlength="4"
                maxlength="4"
                show-word-limit
                @keyup.enter.native="confirmFn()"
              ></el-input>
              <span style="width: 10px;"></span>
              <el-button
                type="primary"
                round
                size="medium"
                v-if="codeFrom.time !== 61"
                disabled
              >请等待{{codeFrom.time}}秒</el-button>

              <el-button
                type="primary"
                round
                size="medium"
                v-else
                @click="refetchFn(codeFrom)"
              >获取验证码</el-button>

            </div>
          </el-form-item>

        </el-form>
      </el-tab-pane>
      <el-tab-pane name="2">
        <el-form
          :model="phoneFrom"
          ref="phoneFrom"
          :rules='phoneRules'
        >
          <el-form-item
            label="手机号"
            prop='phone'
          >
            <el-input
              v-model.trim="phoneFrom.phone"
              show-word-limit
              clearable
              minlength="11"
              maxlength="11"
              @keyup.enter.native="confirmFn()"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane name="3">
        <el-form
          :model="updateFrom"
          ref="updateFrom"
          :rules='updateRules'
          label-width='16%'
        >
          <el-form-item
            label="手机号"
            prop='phone'
          >
            <el-input
              v-model.trim="updateFrom.phone"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="验证码"
            prop='code'
            label-width='80px'
          >
            <div
              class="refetch"
              style="width: 400px ;display: flex"
            >
              <el-input
                style="width: 145px; margin-right: 10px;"
                v-model.trim="updateFrom.code"
                clearable
                minlength="4"
                maxlength="4"
                show-word-limit
                @keyup.enter.native="confirmFn()"
              ></el-input>
              <span style="width: 10px;"></span>
              <el-button
                type="primary"
                round
                size="medium"
                v-if="updateFrom.time !== 61"
                disabled
              >请等待{{updateFrom.time}}秒</el-button>

              <el-button
                type="primary"
                round
                size="medium"
                v-else
                @click="refetchFn(updateFrom)"
              >获取验证码</el-button>

            </div>
          </el-form-item>

        </el-form>
      </el-tab-pane>

    </el-tabs>

    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        @click="cancelFn()"
        v-if="activeName ==='1'"
      >取 消</el-button>
      <el-button
        type="primary"
        @click="confirmFn()"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCodeAPI, newCodeAPI, updatePhoneAPI, validCodeAPI } from '@/api'
import { mapGetters } from 'vuex'
import { validMobile } from '@/utils/validate'
export default {
  name: 'updatePhone',
  props: {
    dialogPhoneVisible: Boolean,
    ActiveName: String
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    return {
      codeFrom: {
        code: '',
        time: 61,
        timer: null
      },
      phoneFrom: {
        phone: ''
      },
      updateFrom: {
        phone: '',
        code: '',
        time: 61,
        timer: null
      },
      codeRules: {
        code: [
          { required: true, message: '验证码不能为空', trigger: 'change' },
          {
            min: 4,
            max: 4,
            type: 'string',
            message: '验证码要求4个字符',
            trigger: 'change'
          }
        ]
      },
      phoneRules: {
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value === '') return callback(new Error('手机号不能为空'))
              if (!validMobile(value)) {
                return callback(new Error('手机号格式有误'))
              }
              callback()
            },
            trigger: 'change'
          }
        ]
      },
      updateRules: {
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value === '') return callback(new Error('手机号不能为空'))
              if (!validMobile(value)) {
                return callback(new Error('手机号格式有误'))
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'change' },
          {
            min: 4,
            max: 4,
            type: 'string',
            message: '验证码要求4个字符',
            trigger: 'change'
          }
        ]
      },
      activeName: this.ActiveName || '1'
    }
  },
  methods: {
    // 点击取消按钮 -> 点击事件
    cancelFn () {
      this.$emit('update:dialogPhoneVisible', false)
    },
    // 点击确定按钮 -> 点击事件
    confirmFn () {
      try {
        switch (this.activeName) {
          case '1':
            this.$refs.codeFrom.validate(async (valid) => {
              if (valid) {
                const { success, code } = await validCodeAPI({
                  ...this.codeFrom,
                  phone: this.userInfo.phone
                })
                if (success && code === 10000) this.activeName = '2'
              }
            })
            break
          case '2':
            this.$refs.phoneFrom.validate(async (valid) => {
              if (valid) {
                const { success, code } = await newCodeAPI(this.phoneFrom)
                if (success && code === 10000) {
                  this.activeName = '3'
                  this.updateFrom.phone = this.phoneFrom.phone
                  this.refetchFn(this.updateFrom)
                }
              }
            })
            break
          case '3':
            this.$refs.updateFrom.validate(async (valid) => {
              if (valid) {
                const { success, code } = await updatePhoneAPI(this.updateFrom)
                if (success && code === 10000) {
                  this.$emit('update:dialogPhoneVisible', false)
                  await this.$store.dispatch('user/getUserInfoActions')
                }
              }
            })
            break
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 弹窗关闭 -> 回调函数
    dialogCloseFn () {
      // 清空表单
      this.codeFrom.code = ''
      this.$refs.codeFrom?.resetFields()
      clearInterval(this.updateFrom.timer)
      this.updateFrom = this.$options.data().updateFrom
      this.$refs.updateFrom?.resetFields()
      this.phoneFrom = this.$options.data().phoneFrom
      this.$refs.phoneFrom?.resetFields()
      clearInterval(this.phoneFrom.timer)
    },
    // 获取验证码 -> 开启定时器
    async refetchFn (from) {
      try {
        const { success, code } = await getCodeAPI()
        if (success && code === 10000) {
          // 提交报名按钮倒计时
          from.timer = setInterval(() => {
            if (from.time === 0) {
              clearInterval(from.timer)
              from.time = 61
            } else from.time--
          }, 1000)
        }
      } catch (err) {
        return console.dir(err)
      }
    }
  },
  // 销毁实例
  beforeDestroy () {
    clearTimeout(this.codeFrom.timer)
    this.codeFrom.timer = null
    clearTimeout(this.updateFrom.timer)
    this.updateFrom.timer = null
  }
}
</script>

<style lang="less" scoped>
.refetch {
  text-align: center;
}
</style>
